package postgres

import (
	"database/sql"

	"quipus/internal/database/dao"
	"quipus/internal/database/postgres/gen/dao/query"
	"quipus/internal/profile"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
	"github.com/pkg/errors"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type PGDB struct {
	db *gorm.DB
}

var q *query.Query

func init() {
	q = nil
}

func (p *PGDB) query() {
	if q == nil {
		q = query.Use(p.db)
	}
}

func NewDB(profile *profile.Profile) (dao.DBOperator, *sql.DB, error) {
	if profile == nil {
		return nil, nil, errors.New("profile is nil")
	}

	// Open the PostgreSQL connection
	gdb, err := gorm.Open(postgres.Open(profile.DSN), &gorm.Config{})

	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to connect to postgres")
	}

	db, error := gdb.DB()
	if error != nil {
		return nil, nil, errors.Wrap(error, "failed to get db handler")
	}

	dbHandler := &PGDB{gdb}

	return dbHandler, db, nil
}

// User model related methods.
